//
//  comInfoPickerViewController.swift
//  NewLndd
//
//  Created by 邵禹曦 on 2020/1/12.
//  Copyright © 2020 辽宁当代. All rights reserved.
//

import UIKit
import PickerView
// MARK: -  商品信息的下拉框
class comInfoPickerViewController: HomeApiViewController, UITableViewDelegate,UITableViewDataSource {
    
    @IBOutlet weak var TableView: UITableView!
    // 定义数组  Use of undeclared type 'Status'  数组 : [模型Model]
    private lazy var ViewModels : [comInfo] = [comInfo]()
    var _comInfo : comInfoPicker?
    var coi : [String] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        showInfo()
    }
}

extension comInfoPickerViewController {
    private func showInfo() {
        // GCD
        let group = DispatchGroup()
       
        // 从沙盒中获取参数
        var userPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        userPath =  (userPath as NSString).appendingPathComponent("data.plist")
        user = NSKeyedUnarchiver.unarchiveObject(withFile: userPath) as? User
        Thread.sleep(forTimeInterval: 0.05)

        // 用户验证
        self.u = user?.U!
        self.retcode = user?.RETCODE!
        let str = [u,"101",retcode]
        //self.isLogin = self._network(str: str as! [String], group: group)
        group.enter()
        NetworkTools.share.check_user(code: str as Array<Any>) { (result, error) in
                      
                          if error != nil {
                              print("no no no")
                              return
                          }
                          

                          if Int(self._retcode(res: result!))! < 0 {
                              self.isLogin = false
                          } else {
                              self.isLogin = true
                          }
                          group.leave()
                      }

        group.notify(queue: DispatchQueue.main) {
            if !self.isLogin {
                return self.setupVisitorView()
            } else {
                Thread.sleep(forTimeInterval: 0.05)
                self.tableShouInfo()
            }
        }
    }
}


extension comInfoPickerViewController {
    // MARK: - TableViewShowInfo
    @objc private func tableShouInfo() {
        // GCD
        let group = DispatchGroup()
        // 获取下拉数据
        let str = [user?.U!,user?.RETCODE! , "", ""]
        group.enter()
        NetworkTools.share.commodity_query(code: str as Array<Any>) { (result, error) in
            
            if error != nil {
                print("no no no")
                return
            }
            
            // 获取可选类型中的数组
            guard let resultArray = result else {
                print("no")
                return
            }
            
            //print(resultArray)
            if let REP = resultArray["REP"] as? [String : AnyObject] {
                if let arr = REP["RESULT"] as? [String : AnyObject]   {
                    let code : Int = Int(arr["RETCODE"] as! String)!
                    if(Int(truncating: NSNumber(value: code)) < 0) {
                        if #available(iOS 13.0, *) {
                            self.showMsgbox(_message: "数据加载失败")
                            return self.setupVisitorView()
                        }
                    }
                }
            }
            
            
            if let REP = resultArray["REP"] as? [String : AnyObject] {
                if let resultList = REP["RESULTLIST"] as? [String : AnyObject] {
                    for temp in resultList["REC"] as! NSArray {
                        let sta = comInfo(dict: temp as! [String : AnyObject])
                        //self.coi.append(sta.COI!)
                        self.ViewModels.append(sta)
                    }
                    // 刷新表格
                    self.TableView.reloadData()
                }
            }
            group.leave()
        }
        
        
        group.notify(queue: DispatchQueue.main) {
            //print(self.coi)
            
        }
    }
}


extension comInfoPickerViewController {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.ViewModels.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : comInfoPickerTableViewCell = tableView.dequeueReusableCell(withIdentifier: "comInfoPickerTableViewCellid") as! comInfoPickerTableViewCell
        cell.ViewModel = ViewModels[indexPath.row]
        
        // 尝试搞按钮
        cell.Btn.tag = indexPath.row
        cell.Btn.addTarget(self, action: #selector(ceBtn), for: .touchUpInside)
        return cell
    }
    
    // cell高
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 32
    }
}


extension comInfoPickerViewController {
    // 每行绑定的button
    @objc private func ceBtn(sender: UIButton!) {
        //self.pickup.ON = self.ViewModels[sender.tag].ON
        
        self._comInfo?.COI = self.ViewModels[sender.tag].COI

        self.performSegue(withIdentifier: "spxl", sender: self.ViewModels[sender.tag].COI)
        
    }
    
    
    // MARK: - 跳转并传参
       override func prepare(for segue: UIStoryboardSegue, sender: Any?)
       {
           if segue.identifier == "spxl" {
               let secVC = segue.destination as! comInfoViewController
                
               //if let indexPath = sender as? comOrder {
                secVC._coi = sender as! String
               //}
           }
       }
}
